//
//  ValueInputController.swift
//  SitPosition
//
//  Created by apple on 2019/1/19.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation
import UIKit
import Cartography


/**
 * 单选列表值选择器
 */
class ValueInputController : UIViewController {
    
    // MARK: - Properties
    
    // 拿到值时的处理回调
    // value: 输入的值
    public var onGotValue: (_ value: String?) -> Void = { _ in }
    public var configuration: (
        _ titleLable: UILabel,
        _ textfield: UITextField,
        _ unitLabel: UILabel) -> Void = { _, _, _ in }
    
    // 面板
    private lazy var panel: UIView = {
        let view = UIView.colored(UIColor.white)
        view.layer.cornerRadius = 2
        return view
    }()
    
    // 标题
    private lazy var titleIconIV: UIImageView = {
        let iv = UIImageView(image: UIImage(named: "tool_continuity"))
        iv.contentMode = .scaleAspectFit
        return iv
    }()
    
    private var titleLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 1
        label.lineBreakMode = .byTruncatingTail
        label.font = Theme.Font.mediumFont(ofSize: 18)
        label.textColor = Theme.Color.primaryDarkTextColor
        label.backgroundColor = UIColor.clear
        return label
    }()
    
    // 输入框背景
    private lazy var inputBKView: UIView = {
        let view = UIView()
        view.backgroundColor = Theme.Color.primaryBackgroundColor
        view.layer.cornerRadius = 2
        return view
    }()
    
    // 输入框
    private lazy var inputTF: UITextField = {
        let tf = UITextField()
        tf.delegate = self
        tf.borderStyle = .none
        tf.clearButtonMode = .whileEditing
        tf.font = Theme.Font.regularFont(ofSize: 24)
        tf.textColor = Theme.Color.primaryDarkTextColor
        tf.backgroundColor = UIColor.clear
        return tf
    }()
    
    // 单位Label
    private lazy var unitLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 1
        label.lineBreakMode = .byTruncatingTail
        label.font = Theme.Font.regularFont(ofSize: 16)
        label.textColor = Theme.Color.lighgrayTextColor
        label.backgroundColor = UIColor.clear
        return label
    }()
    
    // 分隔条
    let horSeperator: UIView = UIView.colored(Theme.Color.seperatorColor)
    let verSeperator: UIView = UIView.colored(Theme.Color.seperatorColor)
    
    // 按钮
    private lazy var cancelBtn: UIButton = {
        let btn = UIButton(type: UIButton.ButtonType.custom)
        btn.setTitleColor(Theme.Color.lighgrayTextColor, for: UIControl.State.normal)
        btn.titleLabel?.font = Theme.Font.regularFont(ofSize: 16)
        btn.addTarget(self, action: #selector(_handleCancel), for: UIControl.Event.touchUpInside)
        btn.setTitle(Strings.cancel, for: UIControl.State.normal)
        return btn
    }()
    
    private lazy var okBtn: UIButton = {
        let btn = UIButton(type: UIButton.ButtonType.custom)
        btn.setTitleColor(Theme.Color.primaryBlueTextColor, for: UIControl.State.normal)
        btn.titleLabel?.font = Theme.Font.regularFont(ofSize: 16)
        btn.addTarget(self, action: #selector(_handleOk), for: UIControl.Event.touchUpInside)
        btn.setTitle(Strings.ok, for: UIControl.State.normal)
        return btn
    }()
    
    // MARK: - Object lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        
        // 子视图
        inputBKView.addSubviews([inputTF, unitLabel])
        panel.addSubviews([titleIconIV,
                           titleLabel,
                           inputBKView,
                           horSeperator,
                           cancelBtn,
                           verSeperator,
                           okBtn])
        view.addSubview(panel)
        _setupConstraints()
        
        // 配置输入框和单位标签
        configuration(titleLabel, inputTF, unitLabel)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 动效
        panel.transform = CGAffineTransform.init(scaleX: 0.5, y: 0.5)
        UIView.animate(withDuration: 0.35, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity:0.5, options: UIView.AnimationOptions.preferredFramesPerSecond60, animations: { [weak self] in
            self?.panel.transform = .identity
        }) { [weak self] _ in
            self?.inputTF.becomeFirstResponder()
        }
    }
    
}


// MARK: - Private Methods

extension ValueInputController {
    
    // 设置视图约束
    func _setupConstraints() {
        let panelH: CGFloat = 190
        let buttonH: CGFloat = 50
        
        // panel
        constrain(panel, view) { v, parent in
            v.top == parent.top + 160
            v.centerX == parent.centerX
            v.width == parent.width * 0.8
            v.height == panelH
        }
        
        // title
        constrain(titleIconIV, panel) { v, parent in
            v.top == parent.top + 19
            v.left == parent.left + 15
            v.width == 19
            v.height == 19
        }
        
        constrain(titleLabel, titleIconIV, panel) { v, sibling, parent in
            v.centerY == sibling.centerY
            v.left == sibling.right + 10
            v.right == parent.right - 15
        }
        
        // inputBKView
        constrain(inputBKView, titleIconIV, panel) { v, sibling, parent in
            v.top == sibling.bottom + 24
            v.left == sibling.left
            v.right == parent.right - 15
            v.height == 50
        }
        
        // input
        constrain(unitLabel, inputBKView) { v, parent in
            v.centerY == parent.centerY
            v.right == parent.right - 15
        }
        unitLabel.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: NSLayoutConstraint.Axis.horizontal)
        unitLabel.setContentCompressionResistancePriority(UILayoutPriority.defaultHigh, for: NSLayoutConstraint.Axis.horizontal)
        
        constrain(inputTF, unitLabel, inputBKView) { v, sibling, parent in
            v.top == parent.top + 10
            v.left == parent.left + 15
            v.right == sibling.left - 8
            v.bottom == parent.bottom - 10
        }
        
        constrain(horSeperator, inputBKView, panel) { v, sibling, parent in
            v.top == sibling.bottom + 28
            v.left == parent.left
            v.right == parent.right
            v.height == 1
        }
        
        // button(s)
        constrain(cancelBtn, horSeperator, panel) { v, sibling, parent in
            v.top == sibling.bottom
            v.left == parent.left
            v.width == parent.width / 2 - 0.5
            v.height == buttonH
        }
        
        constrain(verSeperator, cancelBtn, panel) { v, sibling, parent in
            v.top == sibling.top
            v.centerX == parent.centerX
            v.width == 1
            v.height == sibling.height
        }
        
        constrain(okBtn, cancelBtn, panel) { v, sibling, parent in
            v.top == sibling.top
            v.right == parent.right
            v.width == sibling.width
            v.height == sibling.height
        }
    }
    
    // 取消
    @objc func _handleCancel() {
        onGotValue(nil)
    }
    
    // 确定
    @objc func _handleOk() {
        onGotValue(inputTF.text)
    }
}

// MARK: - UITextFieldDelegate

extension ValueInputController : UITextFieldDelegate {
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}
